import random
from rest_framework.views import APIView
from rest_framework.response import Response
from fuguangeduapi.utils.ronglianyunSms import send_message
from django.conf import settings
from rest_framework import status
from django_redis import get_redis_connection
class SMSApaViews(APIView):
    def get(self,request,mobile):
        # 获取redis链接
        redis = get_redis_connection('sms_code')
        # 默认进入发送短信验证码操作，需要验证是否过期
        # 有限获取当前发送验证码，是否在间隔期
        res_interval = redis.ttl(f"interval_{mobile}")
        if res_interval != -2:
            return Response({"message":"验证码还在有效期，请勿频繁发送验证码"},status=status.HTTP_400_BAD_REQUEST)

        ronglianyun = settings.RONGLIANYUN

        tid = ronglianyun.get('reg_tid')
        sms_expire = ronglianyun.get("sms_expire") # 验证码过期时间
        sms_interval = ronglianyun.get("sms_interval") # 间隔时间，以秒结算
        interval = sms_interval/60
        mobile = mobile
        code = f"{random.randint(0,9999):04d}"
        datas = (
            code,
            interval
        )
        # 发送验证码
        # res = send_message(tid,mobile,datas)
        # 导入异步任务
        from mycelery.sms.tasks import send_sms
        # celery执行异步任务
        send_sms.delay(tid,mobile,datas)

        # redis操作
        # 往redis中保存手机号与验证码
        # 使用redis提供的管道对象，pipeline 优化redis写入操作
        pipe = redis.pipeline()
        pipe.multi()  # 开始事务   保证命令一并发送到服务端，
        redis.setex(f"sms_{mobile}", sms_expire, code)
        redis.setex(f"interval_{mobile}", sms_interval, '-')
        # 提交事务，同时把暂存在pipeline对象中的多条命令，一次性提交给reids
        pipe.execute()

        # if res == "000000":
        #     return Response({"message":"短信发送成功"},status=status.HTTP_200_OK)
        # else:
        #     return Response({"message": "短信发送失败"}, status=status.HTTP_400_BAD_REQUEST)
        return Response({"message": "短信发送成功"}, status=status.HTTP_200_OK)